package com.bupt.service;

import com.bupt.bean.*;
import com.bupt.config.CommonCode;
import com.bupt.config.Result;
import com.bupt.config.RoleResult;
import com.bupt.config.UserResult;
import com.bupt.dao.*;
import com.bupt.ext.UserExt;
import com.bupt.vo.RoleConst;
import com.bupt.vo.SysConst;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
@Transactional
public class UserService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    CompanyUserRepository companyUserRepository;

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    private PrimaryKeyService primaryKeyService;

    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private EntityManager entityManager;

    //查询角色功能点
    public List<Menu> getMenusByRoleId(String roleId){


        //查询角色功能点
        List<Menu> xcMenus = menuMapper.selectPermissionByRoleId(roleId,1,"000000000000000000");
        for (int i = 0; i <xcMenus.size() ; i++) {
            List<Menu> xcMenusTwo = menuMapper.selectPermissionByRoleId(roleId,2,xcMenus.get(i).getId());
            ArrayList<Menu> childrenTwo = new ArrayList<Menu>();
            for (int j = 0; j <xcMenusTwo.size() ; j++) {
                childrenTwo.add(xcMenusTwo.get(j));
                List<Menu> xcMenusthree = menuMapper.selectPermissionByRoleId(roleId,3,xcMenusTwo.get(j).getId());

                ArrayList<Menu> childrenThree = new ArrayList<Menu>();
                for (int k = 0; k <xcMenusthree.size() ; k++) {
                    childrenThree.add(xcMenusthree.get(k));
                    List<Menu> xcMenusfour = menuMapper.selectPermissionByRoleId(roleId,4,xcMenusthree.get(k).getId());
                    ArrayList<Menu> childrenfour = new ArrayList<Menu>();
                    for (int x = 0; x <xcMenusfour.size() ; x++) {
                        childrenfour.add(xcMenusfour.get(x));
                        List<Menu> xcMenusfive = menuMapper.selectPermissionByRoleId(roleId,5,xcMenusfour.get(x).getId());
                        ArrayList<Menu> childrenfive = new ArrayList<Menu>();
                        for (int y = 0; y <xcMenusfive.size() ; y++) {
                            childrenfive.add(xcMenusfive.get(y));
                        }
                        xcMenusfour.get(x).setChildren(childrenfive);
                    }
                    xcMenusthree.get(k).setChildren(childrenfour);
                }
                xcMenusTwo.get(j).setChildren(childrenThree);
            }
            xcMenus.get(i).setChildren(childrenTwo);
        }

        return xcMenus;

    }

    //所有功能点
    public List<Menu> getAllMenus(){


        //查询用户所有权限
        List<Menu> xcMenus = menuMapper.selectAllMenus(1,"000000000000000000");
        for (int i = 0; i <xcMenus.size() ; i++) {
            List<Menu> xcMenusTwo = menuMapper.selectAllMenus(2,xcMenus.get(i).getId());
            ArrayList<Menu> childrenTwo = new ArrayList<Menu>();
            for (int j = 0; j <xcMenusTwo.size() ; j++) {
                childrenTwo.add(xcMenusTwo.get(j));
                List<Menu> xcMenusthree = menuMapper.selectAllMenus(3,xcMenusTwo.get(j).getId());

                ArrayList<Menu> childrenThree = new ArrayList<Menu>();
                for (int k = 0; k <xcMenusthree.size() ; k++) {
                    childrenThree.add(xcMenusthree.get(k));
                    List<Menu> xcMenusfour = menuMapper.selectAllMenus(4,xcMenusthree.get(k).getId());
                    ArrayList<Menu> childrenfour = new ArrayList<Menu>();
                    for (int x = 0; x <xcMenusfour.size() ; x++) {
                        childrenfour.add(xcMenusfour.get(x));
                        List<Menu> xcMenusfive = menuMapper.selectAllMenus(5,xcMenusfour.get(x).getId());
                        ArrayList<Menu> childrenfive = new ArrayList<Menu>();
                        for (int y = 0; y <xcMenusfive.size() ; y++) {
                            childrenfive.add(xcMenusfive.get(y));
                        }
                        xcMenusfour.get(x).setChildren(childrenfive);
                    }
                    xcMenusthree.get(k).setChildren(childrenfour);
                }
                xcMenusTwo.get(j).setChildren(childrenThree);
            }
            xcMenus.get(i).setChildren(childrenTwo);
        }

        return xcMenus;

    }

    //根据账号查询xcUser信息
    public User findXcUserByUsername(String username){
        return userRepository.findByUsername(username);
    }
    //根据账号查询用户权限
    public List<Menu> getUserPermissions(String username){
        //根据账号查询xcUser信息
        User xcUser = this.findXcUserByUsername(username);
        if(xcUser == null){
            return null;
        }
        //用户id
        String userId = xcUser.getId();
        //查询用户所有权限
        List<Menu> xcMenus = menuMapper.selectPermissionByUserId(userId,1,"000000000000000000");
        for (int i = 0; i <xcMenus.size() ; i++) {
            List<Menu> xcMenusTwo = menuMapper.selectPermissionByUserId(userId,2,xcMenus.get(i).getId());
            ArrayList<Menu> childrenTwo = new ArrayList<Menu>();
            for (int j = 0; j <xcMenusTwo.size() ; j++) {
                childrenTwo.add(xcMenusTwo.get(j));
                List<Menu> xcMenusthree = menuMapper.selectPermissionByUserId(userId,3,xcMenusTwo.get(j).getId());

                ArrayList<Menu> childrenThree = new ArrayList<Menu>();
                for (int k = 0; k <xcMenusthree.size() ; k++) {
                    childrenThree.add(xcMenusthree.get(k));
                    List<Menu> xcMenusfour = menuMapper.selectPermissionByUserId(userId,4,xcMenusthree.get(k).getId());
                    ArrayList<Menu> childrenfour = new ArrayList<Menu>();
                    for (int x = 0; x <xcMenusfour.size() ; x++) {
                        childrenfour.add(xcMenusfour.get(x));
                        List<Menu> xcMenusfive = menuMapper.selectPermissionByUserId(userId,5,xcMenusfour.get(x).getId());
                        ArrayList<Menu> childrenfive = new ArrayList<Menu>();
                        for (int y = 0; y <xcMenusfive.size() ; y++) {
                            childrenfive.add(xcMenusfive.get(y));
                        }
                        xcMenusfour.get(x).setChildren(childrenfive);
                    }
                    xcMenusthree.get(k).setChildren(childrenfour);
                }
                xcMenusTwo.get(j).setChildren(childrenThree);
            }
            xcMenus.get(i).setChildren(childrenTwo);
        }

        return xcMenus;

    }

    //根据账号查询用户信息
    public UserExt getUserExt(String username){
        //根据账号查询xcUser信息
        User xcUser = this.findXcUserByUsername(username);
        if(xcUser == null){
            return null;
        }
        //用户id
        String userId = xcUser.getId();
        //查询用户所有权限
        List<Menu> xcMenus = menuMapper.selectPermissionByUserId(userId,1,"000000000000000000");
        for (int i = 0; i <xcMenus.size() ; i++) {
            List<Menu> xcMenusTwo = menuMapper.selectPermissionByUserId(userId,2,xcMenus.get(i).getId());
            ArrayList<Menu> childrenTwo = new ArrayList<Menu>();
            for (int j = 0; j <xcMenusTwo.size() ; j++) {
                childrenTwo.add(xcMenusTwo.get(j));
                List<Menu> xcMenusthree = menuMapper.selectPermissionByUserId(userId,3,xcMenusTwo.get(j).getId());

                ArrayList<Menu> childrenThree = new ArrayList<Menu>();
                for (int k = 0; k <xcMenusthree.size() ; k++) {
                    childrenThree.add(xcMenusthree.get(k));
                    List<Menu> xcMenusfour = menuMapper.selectPermissionByUserId(userId,4,xcMenusthree.get(k).getId());
                    ArrayList<Menu> childrenfour = new ArrayList<Menu>();
                    for (int x = 0; x <xcMenusfour.size() ; x++) {
                        childrenfour.add(xcMenusfour.get(x));
                        List<Menu> xcMenusfive = menuMapper.selectPermissionByUserId(userId,5,xcMenusfour.get(x).getId());
                        ArrayList<Menu> childrenfive = new ArrayList<Menu>();
                        for (int y = 0; y <xcMenusfive.size() ; y++) {
                            childrenfive.add(xcMenusfive.get(y));
                        }
                        xcMenusfour.get(x).setChildren(childrenfive);
                    }
                    xcMenusthree.get(k).setChildren(childrenfour);
                }
                xcMenusTwo.get(j).setChildren(childrenThree);
            }
            xcMenus.get(i).setChildren(childrenTwo);
        }

        /*//根据用户id查询用户所属公司id
        XcCompanyUser xcCompanyUser = companyUserRepository.findByUserId(userId);
        //取到用户的公司id
        String companyId = null;
        if(xcCompanyUser!=null){
            companyId = xcCompanyUser.getCompanyId();
        }*/
        UserExt xcUserExt = new UserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        //xcUserExt.setCompanyId(companyId);
        //设置权限
        xcUserExt.setPermissions(xcMenus);
        return xcUserExt;

    }

    //用户添加
    public UserResult add(String userName, String passWord, String name, String sex, String email, String phone, String roleId) {
        if(userName.equals("")){
            return new UserResult(CommonCode.FAILNAME,new User());
        }
        //校验用户名称
        User byUsername = userRepository.findByUsername(userName);
        if(byUsername==null){
        }else{
            return new UserResult(CommonCode.FAIL,new User());
        }
            if(!sex.equals("1")&&!sex.equals("2")){
            return new UserResult(CommonCode.FAILSEX,new User());
        }

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = new User();
        String id = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
        user.setUsername(userName);
        user.setId(id);
        String encode = new BCryptPasswordEncoder().encode(passWord);
        user.setPassword(encode);
        user.setName(name);
        user.setSex(sex);
        user.setEmail(email);
        user.setPhone(phone);
        user.setUtype("1");
        user.setStatus("1");
        user.setCreateTime(timestamp);
        userRepository.save(user);

        String idrole = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
        UserRole userRole = new UserRole();
        userRole.setId(idrole);
        userRole.setCreateTime(timestamp);
        userRole.setRoleId(roleId);
        userRole.setUserId(id);
        userRoleRepository.save(userRole);

        UserResult result = new UserResult(CommonCode.SUCCESS, user);
        return result;
    }

    //修改用户信息
    public UserResult editUserById(String userId, String userName, String name, String sex, String email, String phone,String roleId) {
        //校验设备名称
        User byUsername = userRepository.findByUsername(userName);
        if(byUsername==null){
        }else{

            if(byUsername.getUsername().equals(userName)){

            }else{
                return new UserResult(CommonCode.FAIL,new User());
            }
        }
        if(!sex.equals("1")&&!sex.equals("2")){
            return new UserResult(CommonCode.FAILSEX,new User());
        }

        //删除原来的
        String sql="delete from user_role  WHERE user_id="+userId;
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int b = nativeQuery.executeUpdate();

        String idrole = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
        UserRole userRole = new UserRole();
        userRole.setId(idrole);
        userRole.setCreateTime(new Timestamp(System.currentTimeMillis()));
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        userRoleRepository.save(userRole);

        Optional<User> byId = userRepository.findById(userId);
        User beforUser = byId.get();

            beforUser.setUsername(userName);
            beforUser.setName(name);
            beforUser.setSex(sex);
            beforUser.setEmail(email);
            beforUser.setPhone(phone);


//        String encode = new BCryptPasswordEncoder().encode(passWord);
//        beforUser.setPassword(encode);
            beforUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));


        User save = userRepository.save(beforUser);
        if (save != null) {
            UserResult userResult = new UserResult(CommonCode.SUCCESS, beforUser);
            return userResult;
        }
        return new UserResult(CommonCode.FAIL, null);
    }

    //删除用户信息
    public Result deleteById(String userId) {
        Result result = new Result();
        //删除用户角色关联
        String sql="delete from user_role  WHERE user_id="+userId;
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int b = nativeQuery.executeUpdate();


        Optional<User> byId = userRepository.findById(userId);
        if(byId.isPresent()){
            User user = byId.get();
            userRepository.deleteById(userId);
            result.setResult("删除成功");
            result.setCode(200);
            return result;
        }

        result.setResult("删除失败");
        result.setCode(404);
        return result;
    }
    //角色添加
    public RoleResult addRole(String roleName, String roleCode, String description) {

        //校验用户名称
        Role byRoleName = roleRepository.findByRoleName(roleName);
        if(byRoleName==null){
        }else{
            return new RoleResult(CommonCode.FAIL,new Role());
        }


        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String id = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
        Role role=new Role();
        role.setRoleName(roleName);
        role.setRole_code(roleCode);
        role.setDescription(description);
        role.setCreate_time(timestamp);
        role.setStatus("1");
        role.setId(id);
        roleRepository.save(role);

        RoleResult result = new RoleResult(CommonCode.SUCCESS, role);
        return result;
    }
//    //角色添加
//    public RoleResult addRole(String roleName, String roleCode, String description, String functions) {
//        if(!functions.contains(",")){
//            return new RoleResult(CommonCode.FAILS,new Role());
//        }
//        //校验用户名称
//        Role byRoleName = roleRepository.findByRoleName(roleName);
//        if(byRoleName==null){
//        }else{
//            return new RoleResult(CommonCode.FAIL,new Role());
//        }
//
//
//        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//        String id = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
//        Role role=new Role();
//        role.setRoleName(roleName);
//        role.setRole_code(roleCode);
//        role.setDescription(description);
//        role.setCreate_time(timestamp);
//        role.setStatus("1");
//        role.setId(id);
//        roleRepository.save(role);
//        String[] split = functions.split(",");
//        for (int i = 0; i <split.length ; i++) {
//            String idp = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
//            Permission permission = new Permission();
//            permission.setCreate_time(timestamp);
//            permission.setRole_id(id);
//            permission.setMenu_id(split[i]);
//            permissionRepository.save(permission);
//
//
//        }
//
//        RoleResult result = new RoleResult(CommonCode.SUCCESS, role);
//        return result;
//    }

//    //修改角色信息
//    public RoleResult editRoleById(String roleId, String roleName, String roleCode, String description, String functions) {
//        if(!functions.contains(",")){
//            return new RoleResult(CommonCode.FAILS,new Role());
//        }
//        //校验设备名称
//        Role byRoleName = roleRepository.findByRoleName(roleName);
//        if(byRoleName==null){
//        }else{
//
//            if(byRoleName.getRoleName().equals(roleName)){
//
//            }else{
//                return new RoleResult(CommonCode.FAIL,new Role());
//            }
//        }
//
//
//        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//        Optional<Role> byId = roleRepository.findById(roleId);
//        Role role = byId.get();
//
//        role.setDescription(description);
//        role.setRole_code(roleCode);
//        role.setRoleName(roleName);
//        role.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//        Role save = roleRepository.save(role);
//
//        //删除原来的
//        String sql="delete from permission  WHERE role_id="+roleId;
//        Query nativeQuery = entityManager.createNativeQuery(sql);
//        int b = nativeQuery.executeUpdate();
//        if(b==0){
//            return new RoleResult(CommonCode.FAIL,new Role());
//        }
//
//
//        String[] split = functions.split(",");
//        for (int i = 0; i <split.length ; i++) {
//            String idp = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
//            Permission permission = new Permission();
//            permission.setCreate_time(timestamp);
//            permission.setRole_id(roleId);
//            permission.setMenu_id(split[i]);
//            //permission.setId(idp);
//            permissionRepository.save(permission);
//        }
//
//        if (save != null) {
//            RoleResult roleResult = new RoleResult(CommonCode.SUCCESS, role);
//            return roleResult;
//        }
//        return new RoleResult(CommonCode.FAIL, null);
//    }
    //修改角色信息
    public RoleResult editRoleById(String roleId, String roleName, String roleCode, String description) {

        //校验设备名称
        Role byRoleName = roleRepository.findByRoleName(roleName);
        if(byRoleName==null){
        }else{

            if(byRoleName.getRoleName().equals(roleName)){

            }else{
                return new RoleResult(CommonCode.FAIL,new Role());
            }
        }


        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Optional<Role> byId = roleRepository.findById(roleId);
        Role role = byId.get();

        role.setDescription(description);
        role.setRole_code(roleCode);
        role.setRoleName(roleName);
        role.setUpdateTime(timestamp);
        Role save = roleRepository.save(role);



        if (save != null) {
            RoleResult roleResult = new RoleResult(CommonCode.SUCCESS, role);
            return roleResult;
        }
        return new RoleResult(CommonCode.FAIL, null);
    }

    //删除角色信息
    public Result deleteByRoleId(String roleId) {
        Result result = new Result();

        String unhandledSql="SELECT COUNT(1)AS COUNT FROM user_role WHERE role_id ="+roleId;
        Query nativeQuerys = entityManager.createNativeQuery(unhandledSql);
        String unhandledCount = nativeQuerys.getResultList().get(0).toString();
        if(!unhandledCount.equals("0")){
            result.setResult("删除失败,请先删除该角色下的用户");
            result.setCode(404);
            return result;
        }

        String sql="delete from permission  WHERE role_id="+roleId;
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int b = nativeQuery.executeUpdate();

        roleRepository.deleteById(roleId);
        result.setResult("删除成功");
        result.setCode(200);
        return result;


    }


    //查询所有角色
    public List<RoleConst> allRole() {
        String sql = "SELECT id,role_name FROM role";
        Query query = entityManager.createNativeQuery(sql);
        List<RoleConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }


    //重置密码
    public Result resetpassword(String userId) {

        Result result = new Result();

        Optional<User> byId = userRepository.findById(userId);
        User beforUser = byId.get();
        String encode = new BCryptPasswordEncoder().encode("123");
        beforUser.setPassword(encode);
        beforUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        User save = userRepository.save(beforUser);
        result.setResult("重置成功");
        result.setCode(200);
        return result;


    }

    //修改用户密码
    public Result updatePassword(String userId,String beforPassword,String newPassword) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        Result result = new Result();

        Optional<User> byId = userRepository.findById(userId);
        User beforUser = byId.get();
        String password = beforUser.getPassword();
        boolean matches = bCryptPasswordEncoder.matches(beforPassword, password);
        System.out.println(matches);
        if(!matches){
            result.setResult("原密码不对");
            result.setCode(404);
            return result;
        }
        String encode = new BCryptPasswordEncoder().encode(newPassword);
        beforUser.setPassword(encode);
        beforUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        User save = userRepository.save(beforUser);
        result.setResult("修改成功");
        result.setCode(200);
        return result;


    }

    //通过ID修改角色权限
    public RoleResult editFunctions(String roleId, String functions) {

                if(!functions.contains(",")){
            return new RoleResult(CommonCode.FAILS,new Role());
        }

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Optional<Role> byId = roleRepository.findById(roleId);
        Role role = byId.get();

                //删除原来的
        String sql="delete from permission  WHERE role_id="+roleId;
        Query nativeQuery = entityManager.createNativeQuery(sql);
        int b = nativeQuery.executeUpdate();



        String[] split = functions.split(",");
        for (int i = 0; i <split.length ; i++) {
            String idp = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID").toString();
            Permission permission = new Permission();
            permission.setCreate_time(timestamp);
            permission.setRole_id(roleId);
            permission.setMenu_id(split[i]);
            //permission.setId(idp);
            permissionRepository.save(permission);
        }


        RoleResult roleResult = new RoleResult(CommonCode.SUCCESS, role);
        return roleResult;
    }

}
